{% extends "base.html" %}
{% load i18n %}
{% load static %}
{% load event_tags %}
{% load display_tags %}

{% block content %}
    {{ block.super }}
    <div class="panel panel-default">
        <div class="panel-heading">
            <div class="clearfix">
                <span class="pull-left">
                  <h4>{{ benchmark_type.name }} {{ benchmark_type.version }} - <span id="head__desired-level">{{ benchmark_product_summary.desired_level }}</span></h4>
                  <span id="head__description">{{ benchmark_product_summary|asvs_level }}</span>
                </span>
                <div id="test-pulldown" class="dropdown pull-right">
                    <form method="post" id="summary" name="summary">{% csrf_token %}
                        {{ benchmark_summary_form.management_form }}
                        {{ benchmark_summary_form.benchmark_type.as_hidden }}
                        {{ benchmark_summary_form.product.as_hidden }}
                        <label for="target">{% trans "Target Level" %}
                            <span class="fa-solid fa-question-circle has-popover" data-trigger="hover"
                                data-content="{% trans "Target ASVS Level for this application." %}"></span>
                        </label>
                        {{ benchmark_summary_form.desired_level }}
                        {{ benchmark_summary_form.score.as_hidden }}
                        <label for="publish">{% trans "Publish" %}
                            <span class="fa-solid fa-question-circle has-popover"
                                 data-trigger="hover"
                                 data-content="{% trans "Publish will display the ASVS Level on the product and other areas in DefectDojo. Check this once you have completed the assessment." %}"></span>
                        </label>
                        {{ benchmark_summary_form.publish }}
                        <button class="btn btn-primary dropdown-toggle"  type="button" id="dropdownMenu1" aria-expanded="false" data-toggle="dropdown" aria-label="Filter options">
                            <i class="fa-solid fa-filter"></i>
                            <span class="caret"></span>
                        </button>
                        <ul class="dropdown-menu dropdown-menu-right" role="menu" aria-labelledby="dropdownMenu1">
                            <li role="presentation">
                                <a title="{{ bc.name }}"
                                   href="{% url 'view_product_benchmark' product.id benchmark_type.id %}">
                                    <span class="fa-solid fa-angle-right"></span> {% trans "View All" %}
                                </a>
                            </li>
                            {% for bc in benchmark_category %}
                                <li role="presentation">
                                    <a title="{{ bc.name }}"
                                       href="{% url 'view_product_benchmark' product.id benchmark_type.id bc.id %}">
                                        <span class="fa-solid fa-list"></span> {{ bc.name }}
                                    </a>
                                </li>
                            {% endfor %}
                        </ul>
                    </form>
                </div>
            </div>
        </div>

        {% if benchmarks %}
            <table id="test_findings" class="table-bordered table table-hover">
                <thead>
                <tr>
                    <th>#</th>
                    <th>{% trans "Description" %}</th>
                    <th class="level1_select">L1</th>
                    <th>L2</th>
                    <th>L3</th>
                    <th>{% trans "Applicable" %}</th>
                    <th>{% trans "Pass" %}</th>
                    <th>{% trans "Notes" %}</th>
                </tr>
                </thead>
                <tbody>
                {% for benchmark in benchmarks %}
                    {% ifchanged %}
                        <tr>
                            <td colspan="8"><b>{{ benchmark.control.category.name }}</b></td>
                        </tr>
                    {% endifchanged %}
                    <tr class="level-{% if benchmark.control.level_1 %}1{% elif benchmark.control.level_2 %}2{% elif benchmark.control.level_3 %}3{% endif %}">
                        <td class="text-center">{{ benchmark.control.objective_number }}</td>
                        <td>{{ benchmark.control.objective | markdown_render }}</td>
                        <td class="text-center">{% if benchmark.control.level_1 %}✓{% endif %}</td>
                        <td class="text-center">{% if benchmark.control.level_2 %}✓{% endif %}</td>
                        <td class="text-center">{% if benchmark.control.level_3 %}✓{% endif %}</td>
                        <td id="td_id_form-{{ benchmark.id }}-enabled" class="text-center">
                            <input type="checkbox" {% if benchmark.enabled %} checked {% endif %} aria-label="{% trans "Is applicable?" %}"
                                   name="form-{{ benchmark.id }}-enabled"
                                   id="id_form-{{ benchmark.id }}-enabled"/>
                        </td>
                        <td id="td_id_form-{{ benchmark.id }}-pass_fail" class="text-center">
                            <input type="checkbox" {% if benchmark.pass_fail %} checked {% endif %} aria-label="{% trans "Is passed?" %}"
                                   name="form-{{ benchmark.id }}-pass_fail" id="id_form-{{ benchmark.id }}-pass_fail"/>
                        </td>
                        <td align="center">
                            <a href="#" onclick="BenchNote.getBenchNotes(this)" data-toggle="modal"
                               data-target="#notesModal"
                               class="fa-solid {% if benchmark.noted %}fa-file-lines{% else %}fa-plus{% endif %}"
                               id="id_form-{{ benchmark.id }}-notes">
                            </a>
                        </td>
                    </tr>
                {% endfor %}
                </tbody>
            </table>
        {% else %}
            <div class="panel-body">
                <p class="text-center">{% trans "No benchmarks found." %}</p>
            </div>
        {% endif %}
    </div>
    <div class="form-group">
        <a class="btn btn btn-danger"
           href="{% url 'delete_product_benchmark' product.id benchmark_type.id %}">{% trans "Delete" %}</a>
    </div>

    {# Modal #}
    <div class="modal fade" id="notesModal" tabindex="-1" role="dialog" aria-labelledby="modal-title" aria-hidden="true">
        <div class="modal-dialog" role="document">
            <div class="modal-content">
                <div class="modal-header">
                    <button type="button" class="close" data-dismiss="modal" aria-label="{% trans "Close" %}"><span
                            aria-hidden="true">&times;</span></button>
                    <h4 id="modal-title" class="modal-title">{% trans "Benchmark Notes" %}</h4>
                </div>
                <div class="modal-body">
                    <div id="benchNotes"></div>
                    <div class="no-notes text-center" style="display: none;">{% trans "There is no notes yet." %}</div>
                    <label for="id_entry">{% trans "Notes:" %}<sup>*</sup></label>
                    <div>
                        <textarea name="entry" cols="15" rows="4" maxlength="2400" required="" id="id_entry"
                                  style="width: 100%"></textarea>
                    </div>
                    <div>
                        <input class="btn btn-primary" onclick="BenchNote.sendBenchNotes()" type="button"
                               value="{% trans "Add Note" %}" id="id_send_notes">
                    </div>
                </div>
            </div>
        </div>
    </div>

{% endblock %}
{% block postscript %}
    {{ block.super }}
    <script>
        function highlight_level(desired_level) {
            switch (desired_level) {
                case "Level 2":
                    level_class = "level-2";
                    break;
                case "Level 3":
                    level_class = "level-3";
                    break;
                default:
                    level_class = "level-1";
                    break
            }
            $('table').removeClass('level-1 level-2 level-3').addClass(level_class);
        }

        function grid_highlight(name, checked) {
            name = '#td_' + name;
            if (checked) {
                $(name).removeClass("benchmark_fail").addClass("benchmark_pass");
            } else {
                $(name).removeClass("benchmark_pass").addClass("benchmark_fail");
            }
        }

        function iterate_checkbox(formname) {
            let value_checked = false;
            $('input[type="checkbox"]').each(function () {
                let check_name = $(this).attr("id")
                if (check_name && (~check_name.indexOf("pass_fail") || ~check_name.indexOf("enabled"))) {
                    disable(check_name);
                    $(this).change(onCheck);
                    if ($(this).is(":checked")) {
                        value_checked = true;
                    }
                    grid_highlight($(this).attr("id"), value_checked)
                    value_checked = false;
                }
            });
        }

        function disable(check_name) {
            if (!check_name) {
                return
            }
            let pass_fail_name = check_name.replace("enabled", "pass_fail");
            let pass_fail = $('#td_' + pass_fail_name);
            let pass_fail_checked = $('#' + pass_fail_name).prop("checked");
            let target_checked = $('#' + check_name).prop("checked");

            if (check_name.indexOf("enable") >= 0) {
                if (target_checked) {
                    $('#' + pass_fail_name).prop('disabled', false);
                    pass_fail.removeClass("benchmark_disabled");
                    pass_fail.addClass("benchmark_fail");
                } else {
                    pass_fail.prop('checked', false);
                    pass_fail.prop('disabled', true);
                    pass_fail.addClass("benchmark_disabled");
                }
            }

            grid_highlight(check_name, target_checked);
            grid_highlight(pass_fail_name, pass_fail_checked);
        }

        function onCheck() {
            let check_name = $(this).attr("id")

            disable(check_name);
            let target_checked = $('#' + check_name).prop("checked");
            let [_, bench_id, field] = check_name.split('-');

            sendAjax("{% url 'update_product_benchmark' product.id benchmark_type.id %}", {
                'bench_id': bench_id,
                'field': field,
                'value': target_checked
            });
        }

        function onPublish() {
            let publish = $(this).prop('checked');

            sendAjax("{% url 'update_product_benchmark_summary' product.id benchmark_type.id benchmark_product_summary.id %}", {
                'field': 'publish',
                'value': publish
            })
        }

        function onChangeDesiredLevel() {
            let desired_level = $('#id_desired_level option:selected').text();
            highlight_level(desired_level);

            sendAjax("{% url 'update_product_benchmark_summary' product.id benchmark_type.id benchmark_product_summary.id %}", {
                'field': 'desired_level',
                'value': desired_level
            })
            .then(response => response.json())
            .then((result) => {
                $('#head__description').text(result.text);
                $('#head__desired-level').text(result.desired_level);
            });
        }

        class BenchNote {
            static bench_id;
            static benchNotes = $('#benchNotes')
            static entry = $('#id_entry')[0]

            static addMessage(note) {
                let div = document.createElement('div');
                div.className = 'bs-callout bs-callout-info';
                div.style = "padding: 20px; margin: 20px 0; border: 1px solid #eee; border-left-width: 5px; border-radius: 3px; border-left-color: #1b809e; padding-top: 10px"
                let self = this;
                let del = document.createElement('p');
                del.style = 'color: red; font-size: 14px; padding: 0px; cursor: pointer; margin-bottom: -12px; margin-left: 99%';
                del.innerText = 'x';
                del.onclick = function () {
                    self.removeNotes(this);
                };
                del.id = `id-${note['id']}-note`;

                let date = document.createElement('p');
                date.style = 'font-size: 10px';
                date.append(note["date"]);

                let author = document.createElement('h4');
                author.append(`${note["author"]}`)
                author.append(date);

                text = document.createElement('span');
                text.append(note['entry']);

                div.append(del);
                div.append(author);
                div.append(text);

                this.benchNotes.append(div);
            }

            static removeNotes(e) {
                if (!confirm("{% trans "Are you sure?" %}")) return;

                BenchNote.spinMeBaby()
                let _id = $(e).attr('id').split('-')[1];

                this.fetchAndUpdate({
                    'bench_id': BenchNote.bench_id,
                    'field': 'delete_notes',
                    'value': _id
                });
            }

            static updateNotes(notes) {
                this.benchNotes.empty();
                let $note_icon = $('#id_form-' + this.bench_id + '-notes');

                if (!notes.length) {
                    $note_icon.removeClass('fa-file-lines').addClass('fa-plus');
                    $('.no-notes').show();
                    return
                }

                $('.no-notes').hide();
                $note_icon.removeClass('fa-plus').addClass('fa-file-lines')
                notes.forEach(note => this.addMessage(note))
            }

            static spinMeBaby() {
                this.benchNotes.empty();

                let div = document.createElement('div');
                div.style = "text-align: center; font-size: 60px";
                let i = document.createElement('i');
                i.className = "fa-solid fa-spinner fa-pulse";

                div.append(i);
                this.benchNotes.append(div);
            }

            static getBenchNotes(self) {
                this.spinMeBaby();
                this.entry.value = '';

                let check_name = self.id;
                let [_, bench_id, field] = check_name.split('-');
                this.bench_id = bench_id;

                this.fetchAndUpdate({
                    'bench_id': this.bench_id,
                    'field': 'get_notes',
                    'value': ''
                });
            }


            static sendBenchNotes() {
                this.spinMeBaby();

                this.fetchAndUpdate({
                    'bench_id': this.bench_id,
                    'field': 'notes',
                    'value': this.entry.value
                });

                this.entry.value = '';
            }

            static fetchAndUpdate(data) {
                sendAjax("{% url 'update_product_benchmark' product.id benchmark_type.id %}", data)
                .then(response => response.json())
                .then(result => BenchNote.updateNotes(result["notes"]));
            }
        }

        function sendAjax(url, data) {
            return fetch(url, {
                method: "POST",
                headers: {
                    'X-CSRFToken': $('input[name=csrfmiddlewaretoken]').val(),
                    'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8'
                },
                body: new URLSearchParams(data)
            });
        }

        $(document).ready(function () {
            //Get the desired ASVS Level
            desired_level = $('#id_desired_level option:selected').text();
            highlight_level(desired_level);
            //Set the pass/fail colors
            iterate_checkbox('summary');
            $("#id_desired_level").change(onChangeDesiredLevel);
            $("#id_publish").change(onPublish);
        });
    </script>
{% endblock %}
{% block add_styles %}
    td p {
        margin-bottom: 0px;
    }

    td p a {
        color: #337ab7;
    }

    .table>tbody>tr>td,
    .table>tbody>tr>th,
    .table>tfoot>tr>td,
    .table>tfoot>tr>th,
    .table>thead>tr>td,
    .table>thead>tr>th {
        padding: 12px 10px
    }

    table.level-1 tr.level-1 td:first-child,
    table.level-2 tr.level-1 td:first-child,
    table.level-3 tr.level-1 td:first-child,
    table.level-2 tr.level-2 td:first-child,
    table.level-3 tr.level-2 td:first-child,
    table.level-3 tr.level-3 td:first-child {
        background-color: #DCEDFB;
    }

    table.level-1 tr.level-2,
    table.level-1 tr.level-3,
    table.level-2 tr.level-3 {
        opacity: 0.55;
    }
{% endblock %}
